package com.share.shareplatform.sharereward.controller;

import com.share.shareplatform.pojo.Provide;
import com.share.shareplatform.pojo.Reward;
import com.share.shareplatform.pojo.Shop;
import com.share.shareplatform.pojo.exception.LogicException;
import com.share.shareplatform.sharereward.service.ProvideService;
import com.share.shareplatform.util.AuthorityUtil;
import com.share.shareplatform.util.Result;
import com.share.shareplatform.util.StringUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import java.util.List;

@RestController
@RequestMapping("/provide")
public class ProvideController{
    
    @Autowired
    private ProvideService provideService;

    @PreAuthorize("hasAuthority('provideAdd')")
    @ApiOperation(value = "推送令添加",notes = "必需字段：rewardId,goodsId\n可选字段：message\n额外说明：如果是超级管理员：需要额外指定userId字段")
    @PostMapping
    public Result addOne(@RequestBody @Validated Provide provide) {
        if(provide.getGoodsId()==null){
            throw new LogicException("请指定商品编号");
        }
        if(provide.getRewardId()==null){
            throw new LogicException("请指定悬赏令id");
        }
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();
            provide.setUserId(userId);
        }else{
            if(provide.getUserId()==null){
                throw new LogicException("请指定用户id");
            }

        }
        Long flag = provideService.addOne(provide);
        if(flag>0){
            return Result.getInstance(200,"添加成功");
        }
        throw new LogicException("添加失败");
    }

    @PreAuthorize("hasAuthority('provideUpdate')")
    @PutMapping
    @ApiOperation(value = "推送令修改",notes = "必需字段：id\n可选字段:goodsId,message")
    public Result updateBaseOne(@RequestBody @Validated Provide provide) {
        if(provide.getId()==null){
            throw new LogicException("请指定id");
        }
        //查询旧的
        Provide oldProvide = provideService.findOneById(provide.getId());
        if(oldProvide==null){
            throw new LogicException("该推送令不存在，无法修改");
        }
        //非管理员
        if (!AuthorityUtil.hasAuthorityUtil("ROLE_admin")) {
            //获取用户jwt中的id
            Long userId =AuthorityUtil.getUserId();

            if (oldProvide.getUserId()!=userId) {
                throw new LogicException("该推送令不不属于你，无法修改");
            }

        }

        Integer flag = provideService.updateBaseOne(provide);
        if(flag>0){
            return Result.getInstance(200,"修改成功");
        }
        throw new LogicException("修改失败");
    }

    @PreAuthorize("hasAuthority('provideDelete')")
    @DeleteMapping("all/{ids}")
    @ApiOperation(value = "推送令删除",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    public Result deleteAllByIds(@PathVariable String ids) {
        List<Long> list = StringUtils.splitStringToLongList(ids);

        if(!AuthorityUtil.hasAuthorityUtil("ROLE_admin")){
            List<Provide> provideList = provideService.findAllByIds(list);
            Long userId = AuthorityUtil.getUserId();
            for(Provide provide:provideList){
                if(provide.getUserId()!=userId){
                    throw new LogicException("该推送令不属于你，无法删除");
                }
            }
        }

        Integer flag = provideService.deleteAllByIds(list);
        return Result.getInstance(200,"删除了"+flag+"条数据");
    }

    @GetMapping("{id}")
    @PermitAll
    @ApiOperation(value = "推送令查询，按id")
    public Result findOneById(@PathVariable Long id) {
        Provide provide = provideService.findOneById(id);
        if(provide==null){
            throw new LogicException("没有找到");
        }
        return Result.getInstance(200,"success").put("provide" ,provide);
    }

    @GetMapping("/page/{pageIndex}/{pageSize}")
    @PermitAll
    @ApiOperation(value = "推送令分页查询",notes = "必需字段：pageIndex(第几页),pageSize（每页大小）")
    public Result findPage(@PathVariable("pageIndex") Integer pageIndex,@PathVariable("pageSize") Integer pageSize) {
        List<Provide> list = provideService.findPage(pageIndex, pageSize);
        return Result.getInstance(200,"success").put("list",list);
    }

    @GetMapping("all/{ids}")
    @PermitAll
    @ApiOperation(value = "推送令批量查询，按id",notes = "其中ids为 'id-id-id' 这种类型的字符串")
    public Result findAllByIds(@PathVariable String ids) {
        List<Long> list = StringUtils.splitStringToLongList(ids);
        List<Provide> provideList = provideService.findAllByIds(list);
        return Result.getInstance(200,"success").put("list",provideList);
    }

    @GetMapping("/all/userId/{id}")
    @PermitAll
    @ApiOperation(value = "推送令查询，按userId")
    public Result findAllByUserId(@PathVariable Long id) {
        List<Provide> list = provideService.findAllByUserId(id);
        return Result.getInstance(200,"success").put("list",list);
    }

    @GetMapping("/all/rewardId/{id}")
    @PermitAll
    @ApiOperation(value = "推送令查询，按rewardId")
    public Result findAllByRewardId(@PathVariable Long id) {
        List<Provide> list = provideService.findAllByRewardId(id);
        return Result.getInstance(200,"success").put("list",list);
    }

}
